package org.nuaa.shr.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ManyObjectiveKnapsack {
	
	private int numberOfObjectives;
	private int numberOfProduct;
	private int[][] profitArray;
	private int[][] weightArray;
	private int[] capacity;
	
	
	
	public ManyObjectiveKnapsack(String profitPath, String weightPath, String capacityPath, int numberOfProduct, int numberOfObjective){
		this.numberOfObjectives = numberOfObjective;
		profitArray = new int[numberOfProduct][numberOfObjective];
		weightArray = new int[numberOfProduct][numberOfObjective];
		capacity = new int[numberOfObjective];
		this.numberOfProduct = numberOfProduct;
		
		try {
			readProblem(profitPath, weightPath, capacityPath);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("read File error!");
		}
	}
	
	private void readProblem(String profitPath, String weightPath, String capacityPath) 
			throws NumberFormatException, IOException {
		InputStream profitIn = getClass().getResourceAsStream(profitPath);
		InputStreamReader profitIsr = new InputStreamReader(profitIn);
		BufferedReader profitBr = new BufferedReader(profitIsr);
		
		InputStream weightIn = getClass().getResourceAsStream(weightPath);
		InputStreamReader weightIsr = new InputStreamReader(weightIn);
		BufferedReader weightBr = new BufferedReader(weightIsr);
		
		
		for(int i = 0;i<numberOfObjectives;i++){
			for(int j = 0;j<numberOfProduct;j++){
				profitArray[j][i] = Integer.parseInt(profitBr.readLine());
				weightArray[j][i] = Integer.parseInt(weightBr.readLine());
			}
		}
		
		InputStream capacityInput = getClass().getResourceAsStream(capacityPath);
		InputStreamReader capacityReader = new InputStreamReader(capacityInput);
		BufferedReader capacityBr = new BufferedReader(capacityReader);
		for(int i = 0;i<numberOfObjectives;i++){
			capacity[i] = Integer.parseInt(capacityBr.readLine());
		}
	}

	public void evaluate(Solution solution){
		
		for(int i = 0;i<solution.getNumberOfObjective();i++){
			int weightSum  = 0;
			int profitSum = 0;
			for(int j = 0;j<solution.getNumberOfVariables();j++){
				int productNumber = solution.getVariable(j);
				weightSum += weightArray[productNumber][i];
				profitSum += profitArray[productNumber][i];
			}
			solution.setConstrain(i, weightSum);
			solution.setObjectives(i, profitSum);
			
		}
	}
	
	public Solution createSolution(){
		return new Solution(numberOfObjectives);
	}
}
